<template>
  <div>
    <!-- 头部 -->
    <div class="header-top">
      <a href="/">
        <img class="img-log" src="../../assets/shishuo.jpg" alt />
      </a>
      <el-link type="danger" :underline="false">教室资源管理系统前台</el-link>

      <span class="header-top-right">
        <el-dropdown type="text" @command="handleCommand">
          <el-button type="text">
            {{toLoginContent}}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :disabled="isDisabledInfo" command="info">个人中心</el-dropdown-item>
            <el-dropdown-item :disabled="isDisabledLogin" command="toLogin">登入</el-dropdown-item>
            <el-dropdown-item :disabled="isDisabledLogout" command="logout">退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </span>
      <span class="avatar">
        <el-avatar size="medium" :src="imgSrc"></el-avatar>
      </span>
    </div>

    <el-dialog title="个人信息" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules"
        ref="ruleForm"
        label-position="left"
        :model="userInfo"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <div>
              <el-form-item label-width="120px">
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost/api/user/avatar/upload/"
                  :show-file-list="false"
                  :with-credentials="true"
                  :headers="headers"
                  name="fileName"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <el-tooltip class="item" effect="dark" content="点击更换头像" placement="top-start">
                    <el-avatar
                      v-loading="loading"
                      element-loading-text="拼命加载中"
                      element-loading-spinner="el-icon-loading"
                      element-loading-background="rgba(0, 0, 0, 0.8)"
                      fit="fit"
                      :size="80"
                      v-if="imgSrc"
                      :src="imgSrc"
                      @error="errorHandler"
                    ></el-avatar>
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-tooltip>
                </el-upload>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div>
              <el-form-item label="学号：" prop="cardNum">
                <el-input
                  :disabled="isDisableCardNum"
                  v-model="userInfo.cardNum"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div>
              <el-form-item label="真实姓名：" prop="username">
                <el-input
                  :disabled="isDisableCardNum"
                  v-model="userInfo.username"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div>
              <el-form-item label="邮箱：" prop="userEmail">
                <el-input
                  :disabled="isDisableCardNum"
                  v-model="userInfo.userEmail"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div>
              <el-form-item label="性别：" prop="userSex">
                <el-radio :disabled="isDisableCardNum" v-model="userInfo.userSex" label="男">男</el-radio>
                <el-radio :disabled="isDisableCardNum" v-model="userInfo.userSex" label="女">女</el-radio>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div>
              <el-form-item label="所在班级：" prop="classesId">
                <el-select
                  class="selectClass"
                  :placeholder="userInfo.className"
                  :disabled="isDisableCardNum"
                  v-model="userInfo.classesId"
                  clearable
                >
                  <el-option
                    v-for="item in classOptions"
                    :key="item.classId"
                    :label="item.className"
                    :value="item.classId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div>
              <el-form-item v-show="! isDisableCardNum" label="密码：" prop="password">
                <el-input
                  :disabled="isDisableCardNum"
                  v-model="userInfo.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <div>
              <el-form-item label="添加时间：">
                <el-input disabled v-model="userInfo.gmtCreate" autocomplete="off"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          v-show="isDisableCardNum == false"
          @click="updateUserInfo('ruleForm')"
        >修 改</el-button>
        <el-button type="warning" @click="dialogFormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-backtop :visibility-height="visibility">
      <div
        style="{
        height: 100%;
        width: 100px;
        background-color: #F2F6FC;
        box-shadow: 0 0 6px rgba(0,0,0, .12);
        text-align: center;
        line-height: 40px;
        color: #1989fa;
        border-radius:25px;
      }"
      >
        <i class="el-icon-caret-top"></i>
      </div>
    </el-backtop>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  data() {
    var checkPwd = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
      let re = new RegExp(reg);
      if (!value) {
        return callback(new Error("密码不能为空"));
      } else if (!re.test(value)) {
        return callback(new Error("密码只能是数字与字母组合，且6-16位"));
      } else {
        callback();
      }
    };
    return {
      // 未登录显示（登录），已登录则将数改为名字
      toLoginContent: "欢迎使用",
      // 登录按钮是否被禁用
      isDisabledLogin: false,
      isDisabledLogout: true,
      isDisabledInfo: true,
      // 头像地址
      imgSrc: "",
      //触发显示回到顶部按钮
      visibility: 20,
      userInfo: {
        userId: 1233,
        cardNum: "",
        username: "",
        userEmail: "",
        userSex: "",
        gmtCreate: "",
        className: "",
        classesId: "",
        password: ""
      },
      dialogFormVisible: false,

      loading: false,
      rules: {
        cardNum: [
          { required: true, message: "学号不能为空", trigger: "blur" },
          { min: 9, max: 9, message: "学号是9位", trigger: "blur" }
        ],
        password: [{ validator: checkPwd, trigger: "blur" }],
        classesId: [
          { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "change" }
        ],
        userEmail: [
          {
            type: "email",
            required: true,
            message: "邮箱格式不对",
            trigger: "change"
          }
        ],

        userSex: [
          {
            required: true,
            message: "性别不能为空",
            trigger: "change"
          }
        ],
        resource: [
          { required: true, message: "请选择活动资源", trigger: "change" }
        ],
        desc: [{ required: true, message: "请填写活动形式", trigger: "blur" }]
      },
      headers: {},
      isDisableCardNum: true,
      classOptions: [
        {
          id: 1,
          className: ""
        }
      ]
    };
  },
  created() {
    // 获取路径的token值，如果token值不为空，将token放入sessionStorage,然后重定向将token去掉
    let token = this.$route.query.token;
    if (token) {
      sessionStorage.setItem("USER-TOKEN", token);
      location.href = "http://localhost:8081/#/welcome";
    }
    this.getUserInfo();
    this.getUserAvatar();
  },
  methods: {
    errorHandler() {
      return true;
    },
    updateUserInfo(ruleForm) {
      let params = new URLSearchParams();
      params.append("cardNum", this.userInfo.cardNum);
      params.append("username", this.userInfo.username);
      params.append("userEmail", this.userInfo.userEmail);
      params.append("userSex", this.userInfo.userSex);
      params.append("classesId", this.userInfo.classesId);
      params.append("password", this.userInfo.password);
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          this.$http
            .put("/user/userEntity", params)
            .then(resp => {
              let { msg, code } = resp.data;
              if (code == 1) {
                this.$message.success("修改成功，请重新登录！");
                this.logout();
                this.$router.push("/login");
                return;
              }
              this.$message.warning(msg);
            })
            .catch(resp => {});
        } else {
          this.$message.info("个人信息不完整");
          return false;
        }
      });
    },
    // 获取用户信息
    getUserInfo() {
      this.$http
        .get("/auth/userInfo")
        .then(resp => {
          let { msg, data, code } = resp.data;
          if (code == 1) {
            this.userInfo.userId = data.userId;
            // 根据id调用接口获取头像
            this.toLoginContent = "欢迎您！ " + data.username;
            this.isDisabledLogin = true;
            this.isDisabledLogout = false;
            this.isDisabledInfo = false;
          }
        })
        .catch(resp => {});
    },
    // 获取头像信息
    getUserAvatar() {
      this.$http
        .get("/user/avatar")
        .then(resp => {
          let { msg, data, code } = resp.data;
          if (code == 1) {
            this.imgSrc = data.user.img;
            this.headers.token = sessionStorage.getItem("USER-TOKEN");
          } else {
            this.$message.error(msg);
          }
        })
        .catch(resp => {});
    },
    getUserDetails() {
      this.$http
        .get(`/user/userId/`)
        .then(resp => {
          let { msg, data, code } = resp.data;
          if (code == 1) {
            let cardNum = data.user.cardNum;
            if (!cardNum) {
              this.isDisableCardNum = false;
            }
            this.userInfo = data.user;
          } else {
            this.$message.error(msg);
          }
        })
        .catch(resp => {});
    },
    // 退出操作
    logout() {
      sessionStorage.removeItem("USER-TOKEN");
      this.imgSrc =
        "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png";
      this.toLoginContent = "欢迎使用";
      this.isDisabledLogin = false;
      this.isDisabledLogout = true;
      this.isDisabledInfo = true;
      this.$notify({
        title: "退出成功",
        message: "谢谢使用",
        position: "top-left",
        type: "success",
        duration: 1200
      });
    },
    // 下拉处理
    handleCommand(param) {
      if (param == "info") {
        // 获取用户详情
        this.getUserDetails();
        this.getAllClassList();
        // 打开dialog
        this.dialogFormVisible = true;
      } else if (param == "logout") {
        return this.logout();
      } else if ((param = "toLogin")) {
        return this.$router.push("/login");
      }
    },
    // 上传头像成功后调用的方法
    handleAvatarSuccess(res, file) {
      // 重新获取数据
      this.getUserAvatar();
      this.loading = false;
      this.$message.success("头像更新成功");
    },
    // 上传头像成功前调用的方法
    beforeAvatarUpload(file) {
      this.loading = true;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    getAllClassList() {
      this.$http
        .get("class/noAuthorize/all/class")
        .then(resp => {
          let { code, msg, data } = resp.data;
          if (code == 1) {
            this.classOptions = data.classesList;
          }
        })
        .catch(resp => {});
    }
  }
};
</script>

<style scoped>
.header-top {
  height: 50px;
}
.header-top-right {
  float: right;
  font-size: 18px;
  margin-top: 6px;
}
.img-log {
  width: 50px;
  height: 50px;
  border-radius: 15px;
  margin-top: 4px;
}
.el-link {
  margin-top: 15px;
  margin-right: 10px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.avatar {
  float: right;
  margin-right: 10px;
  margin-top: 8px;
}
.el-backtop {
  margin-right: 220px;
}
.el-form-item {
  margin-left: 20px;
}
.el-input {
  width: 180px;
}
.avatar-uploader {
  margin-left: 130px;
}
.selectClass {
  width: 180px;
}
.el-link {
  /* border: 1px solid white; */
  font-size: 20px;
  margin-bottom: 55px;
  margin-left: 15px;
}
</style>